﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;

namespace OneCaps.DB
{
    // Infrastructure/Data/SqlSugar/SqlSugarRepository.cs
    public class SqlSugarRepository<TEntity, TKey> : IRepository<TEntity, TKey>
        where TEntity : class, new()
    {
        private readonly ISqlSugarClient _db;

        public SqlSugarRepository(ISqlSugarClient db)
        {
            _db = db;
        }

        public async Task<TEntity> GetByIdAsync(TKey id)
        {
            return await _db.Queryable<TEntity>().InSingleAsync(id);
        }

        public async Task<IEnumerable<TEntity>> GetAllAsync()
        {
            return await _db.Queryable<TEntity>().ToListAsync();
        }

        public async Task<IEnumerable<TEntity>> FindAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await _db.Queryable<TEntity>().Where(predicate).ToListAsync();
        }

        public async Task AddAsync(TEntity entity)
        {
            await _db.Insertable(entity).ExecuteReturnEntityAsync();
        }

        public async Task AddRangeAsync(IEnumerable<TEntity> entities)
        {
            await _db.Insertable(entities.ToList()).ExecuteCommandAsync();
        }

        public async Task UpdateAsync(TEntity entity)
        {
            await _db.Updateable(entity).ExecuteCommandAsync();
        }

        public async Task UpdateRangeAsync(IEnumerable<TEntity> entities)
        {
            await _db.Updateable(entities.ToList()).ExecuteCommandAsync();
        }

        public async Task DeleteAsync(TKey id)
        {
            await _db.Deleteable<TEntity>(id).ExecuteCommandAsync();
        }

        public async Task DeleteAsync(TEntity entity)
        {
            await _db.Deleteable(entity).ExecuteCommandAsync();
        }

        public async Task<int> SaveChangesAsync()
        {
            // SqlSugar 自动提交事务，通常无需显式调用
            return 1;
        }
    }
}
